package com.pai4j.aigc.controller;

import com.pai4j.aigc.llm.entity.LLMModelEntity;
import com.pai4j.aigc.llm.entity.LLMUserBindingEntity;
import com.pai4j.aigc.llm.service.LLMModelService;
import com.pai4j.common.bean.PAIResponseBean;
import com.pai4j.common.bean.PAIResponseBeanUtil;
import com.pai4j.domain.dto.llmconfig.LLMUserBindDTO;
import com.pai4j.log.annotation.OperationLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/aigc/user/llm")
public class LLMModelUserController {

    @Autowired
    private LLMModelService modelService;

    @GetMapping("/available-models")
    public PAIResponseBean<List<LLMModelEntity>> availableModels(@RequestParam String tenantId) {
        List<LLMModelEntity> list = modelService.listEnabledModels(tenantId)
                .stream().peek(m -> m.setApiKey(null))
                .collect(Collectors.toList());
        return PAIResponseBeanUtil.success(list);
    }

    @GetMapping("/current")
    public PAIResponseBean<LLMModelEntity> current(@RequestParam String tenantId, @RequestParam String userId) {
        Optional<LLMModelEntity> model = modelService.findActiveModelForUser(tenantId, userId)
                .or(() -> modelService.getDefaultModel(tenantId));
        LLMModelEntity masked = model.map(m -> {
            m.setApiKey(null);
            return m;
        }).orElse(null);
        return PAIResponseBeanUtil.success(masked);
    }

    @PostMapping("/bind")
    @OperationLog(module = "AIGC管理", operation = "用户绑定LLM模型", description = "用户设置自己的默认LLM模型", recordParams = false)
    public PAIResponseBean<LLMUserBindingEntity> bind(@RequestBody LLMUserBindDTO dto) {
        LLMUserBindingEntity binding = modelService.bindUserModel(dto.getTenantId(), dto.getUserId(), dto.getModelId(), dto.getOperator());
        return PAIResponseBeanUtil.success(binding);
    }
}
